import { createRouter, createWebHashHistory } from 'vue-router';
import axios from "@/utils/axios";

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'Login',
        component: ()=> import('../views/login.vue'),
    },
    {
        path: '/terms',
        name: 'Terms',
        component: ()=> import('../views/terms.vue'),
    },
    {
        path: '/main',
        component: () => import('../views/main.vue'),
        meta: { requiresAuth: true },
        children: [
            {
                path: '',
                redirect: '/main/dashboard'
            },
            {
                path: 'dashboard',
                name: 'Dashboard',
                component: () => import('../views/dashboard.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'user',
                name: 'User',
                component: () => import('../views/user.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'posts/review',
                name: 'PostsReview',
                component: () => import('../views/review.vue'),
                meta: { requiresAuth: true }
            },
            {
                path:'posts/manage',
                name: 'PostsManage',
                component: () => import('../views/manage.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'comments',
                name: 'Comments',
                component: () => import('../views/comments.vue'),
                meta: { requiresAuth: true }
            },
            {
                path:'/tags',
                name: 'Tag',
                component: () => import('../views/tag.vue'),
                meta: { requiresAuth: true }
            },
            {
                path:'/games',
                name: 'Game',
                component: () => import('../views/game.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'admin',
                name: 'Admin',
                component: () => import('../views/admin.vue'),
                meta: { requiresAuth: true, requiresSuperAdmin: true }
            },
            {
                path: 'permission-test',
                name: 'PermissionTest',
                component: () => import('../views/permission-test.vue'),
                meta: { requiresAuth: true }
            }
        ]
    },
];

const router = createRouter({
    history: createWebHashHistory(),
    routes
});

// 全局守卫：检查是否需要登录
router.beforeEach(async (to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
        const token = localStorage.getItem('token');
        if (!token) {
            next({ path: '/login', query: { redirect: to.fullPath } });
        } else {
            try {
                // 向后端发送 token 验证请求
                const response = await axios.get('/admin/check', {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                if (response.code === 200) {
                    // 检查是否需要超级管理员权限
                    if (to.matched.some(record => record.meta.requiresSuperAdmin)) {
                        try {
                            const userResponse = await axios.get('/admin/current',{
                                headers: { 'Authorization': `Bearer ${token}` }
                            });
                            if (userResponse.code === 200 && userResponse.data.admin_role === 2) {
                                next(); // 是超级管理员，放行
                            } else {
                                ElMessage.error('权限不足，需要超级管理员权限');
                                next('/main/dashboard'); // 权限不足，跳转到首页
                            }
                        } catch (error) {
                            ElMessage.error('获取用户信息失败');
                            next('/main/dashboard');
                        }
                    } else {
                        next(); // token 有效，放行
                    }
                } else {
                    localStorage.removeItem('token');
                    next('/login'); // token 无效，跳转登录
                }
            } catch (error) {
                localStorage.removeItem('token');
                next('/login'); // 请求失败，跳转登录
            }
        }
    } else {
        next(); // 不需要认证的路由
    }
});

export default router;